package com.yphone.base.utils;

import android.content.Context;
import android.util.Base64;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class SharepreferenceUtils {


    public static <T> T jsonToClass(String string) {
        try {
            ObjectInputStream objectInputStream = new ObjectInputStream(new ByteArrayInputStream(Base64.decode(string.getBytes(), 0)));
            T list = (T) objectInputStream.readObject();
            objectInputStream.close();
            return list;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


    public static <T> T jsonToClass(Context context, String fileName, String nodeName) {
        try {
            String json = MySharepreferenceUtil.getSharePreString(context, fileName, nodeName, "");
            if (json.equals("")) {
                return null;
            }
            return jsonToClass(json);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }



    public static <T> void saveClass(Context context, String fileName, String nodeName, T list) {
        try {
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
            objectOutputStream.writeObject(list);
            String listBase64 = new String(Base64.encode(byteArrayOutputStream.toByteArray(), 0));
            objectOutputStream.close();
            MySharepreferenceUtil.putSharePreStr(context, fileName, nodeName, listBase64);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
